var express = require('express');
var app = express();
var http = require('http').Server(app);
var bodyParser = require('body-parser');
var session = require('express-session');
var s_db = require('./dbwrap_construct.js');
var fs = require('fs');
var log_start = require('../lib/log_start.js');
var SMSClient = require('@alicloud/sms-sdk');
var child_process = require('child_process');
var methods = require('methods');
var tcpcache = require('./tcpcache.js');
var dgram = require('dgram');
var client = dgram.createSocket('udp4');
var md5 = require("md5");
var get = require('../lib/get.js');
var post = require('../lib/post.js');
var encoding = require('encoding');
var public_fun = require('../lib/public_fun.js');
var pub_config = require('./construct_config.js');
//在线
app.use(bodyParser.urlencoded({ extended: false }))
app.use(bodyParser.json());
app.all('*', function (req, res, next) {
    res.header("Access-Control-Allow-Origin", req.headers.origin);
    res.header("Access-Control-Allow-Credentials", true);
    res.header("Access-Control-Allow-Headers", "X-Requested-With,Content-Type");
    res.header("Access-Control-Allow-Methods", "PUT,POST,GET,DELETE,OPTIONS");
    res.header("X-Powered-By", 'BIM');
    next();
});

app.use(express.static(__dirname + '/app'));

app.use(session({
    secret: 'secret',
    resave: true,
    saveUninitialized: false,
    cookie: {
        maxAge: 1000 * 60 * 10 * 5//过期时间设置(单位毫秒)
    }
}));
app.use(function (req, res, next) {
    var url = req.url;
    if (url == '/userlogin' || url.indexOf('/sensor_data') >= 0 || url.indexOf('/wx_login2') >= 0) {
        next();
        return;
    }
    if (!req.session.user) {
        res.send({ ret: -3, info: "session过期" });
        return;
    } else if (req.session.user) {
        next();
    }
});


// 通过启动子进程启动tcpserver
// var tcpserver_start = child_process.fork(__dirname+'/tcpserver.js');
// tcpserver_start.on('message', function (m) {
//     console.log('PARENT got message:', m);
// });
function server_db() {
    return s_db;
}
function isJSON(str) {
    if (typeof str == 'string') {
        try {
            var obj = JSON.parse(str);
            return true;
        } catch(e) {
            return false;
        }
    }else{
        return false;
    }
}
// ************************函数*****************************
// ********************施工管理接口******************************
// **********************公用接口********************************
function post_select_data(req, res, tablename, fields) {
    var page = null;
    if (req.body.page) {
        page = req.body.page;
    } else {
        page = req.body.currentPage;
    }
    var limit = req.body.rows;
    var sidx = req.body.sidx;
    var sord = req.body.sord;
    if (sidx == null)
        sidx = 1;
    if (page == null)
        page = 1;
    if (limit == null)
        limit = 10;
    server_db().db_info_type_page(req, fields, tablename, page, limit, sidx, sord, function (ret, info) {
        info.ret = ret;
        res.send(info);
    });
};

// 项目：1：代表项目编辑权限、2：代表设备编辑权限、4：代表查看权限
function project_power(power, num) {
    var arr_pro = [];
    if (isJSON(power) == true) {
        power = JSON.parse(power);
        for (var i = 0; i < power.length; i++) {
            var projectid = power[i].projectid;
            var current_power = power[i].power;
            if ((current_power & num) == num) {
                arr_pro.push(projectid);
            }
        }
    }
    return arr_pro;
}
// **********************前台接口********************************
// 账号密码登录
app.post('/userlogin', function (req, res) {
    var id = req.body.id;
    var pass = req.body.pass;
    var tablename = 'user';
    if (id == null || pass == null) {
        res.sendStatus(404);
        return;
    }
    else {
        pass = md5(pass);
        var query = {
            id: "=" + id,
            pass: "=" + pass
        };
        server_db().db_get_detailuser(tablename, query, function (ret, info, power) {
            if (ret == -1) {
                res.send({ ret: -1 });
            }
            else if (ret == 0) {
                res.send({ ret: 0 });
            }
            else if (ret == 1) {
                req.session.user = id;
                if (info.fid == '1') {//管理员
                    req.session.power = 'all';
                    req.session.fid = id;
                } else if (info.fid == '0') {//超级管理员
                    req.session.power = 'administrator';
                    req.session.fid = info.fid;
                } else {//普通用户
                    req.session.fid = info.fid;
                    req.session.power = power;
                }
                res.send({ ret: 1, info: info, power: req.session.power });
            }
        });
    }
});
// 微信登录
// 微信客户端的公众号获取
app.post('/wx_login2', function (req, res) {
    // var url_user = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid=wxe9b3a49046f23992&redirect_uri=http%3A%2F%2Fwww.sxzd365.com%2Fwx_login2&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect';
    // console.log('wx_login2',req.body);
    var info = req.body.info;
    var fid = req.body.fid;
    if (info == null || info == '') {
        res.send({ret:-1,info:'no'});
        return;
    }
    if (fid == null || info == '') {
        res.send({ret:-2,info:'no fid'});
        return;
    }
    var sex = '保密';
    if (info.sex == 2) {
        sex = '女';
    }else if (info.sex == 1) {
        sex = '男';
    }
    var data  = {
        id:info.nickname + (new Date().getTime()),
        wx_openid:info.openid,
        pic:info.headimgurl,
        fid:fid,
        sex:sex,
        name:info.nickname,
        city:info.city
    }
    // 查询该用户存在不
    var query = {
        wx_openid:info.openid
    }
    server_db().db_get_detailuser('user', query, function (ret, info, power) {
            // console.log(ret,info,power);
            if (ret != 1) {//用户不存在，插入数据库
                server_db().db_info_insert(data, 'user', function (ret2, info2) {
                    // console.log(ret2,info2);//1,0
                    if (ret2 === 1) {
                      req.session.user = data.id;
                      req.session.fid = data.fid;
                      req.session.power = '0';
                      res.send({ ret: 1, info: data, power: req.session.power });
                    }
                });
            }            
            else if (ret == 1) {
                req.session.user = info.id;
                if (info.fid == '1') {//管理员
                    req.session.power = 'all';
                    req.session.fid = info.id;
                } else if (info.fid == '0') {//超级管理员
                    req.session.power = 'administrator';
                    req.session.fid = info.fid;
                } else {//普通用户
                    req.session.fid = info.fid;
                    req.session.power = power;
                }
                res.send({ ret: 1, info: info, power: req.session.power });
                // res.redirect('/#/data');
            }
    });
    // 网站扫码获取
    // var url = 'https://api.weixin.qq.com/sns/oauth2/access_token?appid=' + appid + '&secret=' + secret + '&code=' + code + '&grant_type=authorization_code';
});
app.get('/logout', function (req, res) {
    req.session.user = null;
    req.session.error = null;
    res.redirect('/login.html');
});
app.get('/session_user', function (req, res) {
    // console.log(req.session.fid);
    server_db().db_get_detail('user',{id:req.session.user},function(ret,info){
        if (ret == 1) {
          res.send({ ret: 1, user: req.session.user, fid: req.session.fid, power: req.session.power,info:info});
        }else{
            res.send({ret:-1});
        }
    })
    
});
// **********************后台接口*************************************

// ***************************get接口***************************************
// 获取设备类型
app.get('/device_types', function (req, res) {
    var info = pub_config.device_types;
    res.send({ ret: 1, info: info });
});
// 获取参数类型
app.get('/params_types', function (req, res) {
    var info = pub_config.par_types;
    res.send({ ret: 1, info: info });
});
/* 类型获取
   req.params.type可能值：
   notice_type:通知类型(处理类型)
   par_types：参数类型
   device_types：设备类型
*/
app.get('/public_types/:type',function(req,res){
    var type = req.params.type;
    if (type == null || type == '') {
        res.send({ret:-1,info:'no type'});
        return;
    }
    var info = pub_config[type];
    res.send({ret:1,info:info});
})
// 获取设备类型的名称
app.get('/device_types/:id', function (req, res) {
    var info = pub_config.device_types;
    var id = req.params.id;
    if (id == null || id == '') {
        res.send({ ret: -1, info: '没有id' });
        return;
    }
    var name = '';
    for (var i = 0; i < info.length; i++) {
        var obj = info[i];
        if (id == obj.id) {
            name = obj.name;
            break;
        }
    }
    res.send({ ret: 1, info: name });
});
// 查询详情数据 (url?a==1) 单条数据
app.get('/detail/:table', function (req, res) {
    var query = req.query;
    var tablename = req.params.table;
    if (tablename == null || query == null) {
        res.sendStatus(404);
        return;
    }
    else {
        server_db().db_get_detail(tablename, query, function (ret, info) {
            res.send({ ret: ret, info: info });
        });
    }
});
//2.0 获取数据不分页  url?a==1
app.get("/list_nopage/:table", function (req, res) {
    var table = req.params.table;
    if (table == null || table == "") {
        res.sendStatus(404);
        return;
    }
    var fields = '*';
    var power = req.session.power;
    if (power == '' || power == '0' || power == null) {
        res.send({ ret: 1, info: [] });
        return;
    } else if (power == 'all') {
        req.query.fid = req.session.fid;

    } else if (power == 'administrator') {

    } else if (isJSON(power) == true) { //有权限的普通用户
        var arr_pro = project_power(power, 4);
        if (arr_pro.length <= 0) {
            res.send({ ret: 1, info: [] });
            return;
        }
        if (table == "project") {//通过项目id获取项目列表
            req.field_arr = arr_pro;
            req.field = 'id';
        }
        else if (table == "device" || table == pub_config.devicelog || table.indexOf(pub_config.devicelog2) >= 0) {//通过项目id获取设备列表,log列表
            req.field_arr = arr_pro;
            req.field = 'projectid';
        }
    } else {
        res.send({ ret: 1, info: [] });
        return;
    }
    server_db().db_select_list(req.field, req.field_arr, req.query, fields, table, null, null, function (ret, info) {
        res.send({ ret: ret, info: info });
    });
});

// 2.1 不分页  url?a==1
app.get("/select_idname/:table", function (req, res) {
    var table = req.params.table;
    var fields = 'id,name';
    if (table == null || table == "") {
        res.sendStatus(404);
        return;
    }
    var power = req.session.power;
    if (power == '' || power == '0' || power == null) {
        res.send({ ret: 1, info: [] });
        return;
    } else if (power == 'administrator') {

    } else if (power == 'all') {
        req.query.fid = req.session.fid;
    } else if (isJSON(power) == true) {
        var arr_pro = project_power(power, 4);
        if (table == 'project') {
            if (arr_pro.length > 0) {
                server_db().db_select_where_in('id', arr_pro, fields, table, function (ret, info) {
                    res.send({ ret: 1, info: info });
                })
            } else {
                res.send({ ret: 1, info: [] })
            }
            return;
        } else {
            req.query.fid = req.session.fid;
        }
    } else {
        res.send({ ret: 1, info: [] });
        return;
    }
    server_db().db_select_list(null, null, req.query, fields, table, null, null, function (ret, info) {
        res.send({ ret: ret, info: info });
    });
});
// 2.1 不分页  获取所有的设备
app.get("/select_deviceid", function (req, res) {
    var table = 'device';
    var fields = 'id,deviceid';
    var power = req.session.power;
    if (power == '' || power == '0' || power == null) {
        res.send({ ret: 1, info: [] });
        return;
    } else if (power == 'administrator') {

    } else if (power == 'all') {
        req.query.fid = '=' + req.session.fid;
    } else if (isJSON(power) == true) {
        var arr_pro = project_power(power, 4);
        if (arr_pro.length <= 0) {
            res.send({ ret: 1, info: [] });
            return;
        }
        server_db().db_select_list('projectid', arr_pro, req.query, fields, table, null, null, function (ret, info) {
            res.send({ ret: ret, info: info });
        });
        return;
    } else {
        res.send({ ret: 1, info: [] });
        return;
    }
    server_db().db_select_list(null, null, req.query, fields, table, null, null, function (ret, info) {
        res.send({ ret: ret, info: info });
    });
});
// 2.2 不分页  获取所有的端口号
app.get("/select_ports", function (req, res) {
    var table = 'protocol';
    var fields = 'id,port';
    var power = req.session.power;
    if (power == '' || power == '0' || power == null) {
        res.send({ ret: 1, info: [] });
        return;
    } else if (power == 'administrator') {

    } else if (power == 'all') {
        req.query.fid = '=' + req.session.fid;
    } else if (isJSON(power) == true) {
        req.query.fid = '=' + req.session.fid;
    } else {
        res.send({ ret: 1, info: [] });
        return;
    }
    server_db().db_select_list(null, null, req.query, fields, table, null, null, function (ret, info) {
        res.send({ ret: ret, info: info });
    });
});
// 不分页历史数据曲线：查询指定字段 url?deviceid=1&time=2017-01-01,2017-02-02
app.get("/history_data", function (req, res) {
    var table = pub_config.devicelog;
    var fields = 'press,temp,time';
    var power = req.session.power;
    if (power == '' || power == '0' || power == null) {
        res.send({ ret: 1, info: [] });
        return;
    } else if (power == 'administrator') {
        server_db().db_select_list(null, null, req.query, fields, table, 'time', 'asc', function (ret, info) {
            res.send({ ret: ret, info: info });
        });
    } else if (power == 'all') {
        // 获取设备id
        req.query.fid = '=' + req.session.fid;
        server_db().db_select_list(null, null, req.query, fields, table, 'time', 'asc', function (ret1, info1) {
            res.send({ ret: ret1, info: info1 });
        });
    } else if (isJSON(power) == true) {
        var arr_pro = project_power(power, 4);
        if (arr_pro.length <= 0) {
            res.send({ ret: 1, info: [] });
            return;
        }
        server_db().db_select_list('projectid', arr_pro, req.query, fields, table, 'time', 'asc', function (ret1, info1) {
            res.send({ ret: ret1, info: info1 });
        });
    } else {
        res.send({ ret: 1, info: [] });
        return;
    }

})
//数据修改,历史数据图表
/*
 query 里面包含
    var time = query.time;
    var timetype = query.timetype;
    var field = query.field;
    var deviceid = query.deviceid;
*/
app.get("/history_curve_test", function (req, res) {
    var obj = req.query;
    var port = "8053";//obj.port;
    var time = obj.time;
    var timetype = obj.timetype;
    var field = obj.field;
    var deviceid = obj.deviceid;
    server_db().db_get_time_curve_data(port, deviceid, time, timetype, field, function (ret, info) {
        res.send({ ret: ret, info: info });
    });
});
app.get("/history_curve_1", function (req, res) {
    var power = req.session.power;

    var obj = req.query;
    var port = "8053";//obj.port;
    var time = obj.time;
    var timetype = obj.timetype;
    var field = obj.field;
    var deviceid = obj.deviceid;
    if (power == '' || power == '0' || power == null) {
        res.send({ ret: -4, info: '没有权限' });
        return;
    } else if (power == 'administrator') {//超级管理员
        server_db().db_get_time_curve_data(port, deviceid, time, timetype, field, function (ret, info) {
            res.send({ ret: ret, info: info });
        });
    } else if (power == 'all') {//管理员
        // 获取设备id
        //req.query.fid = '=' + req.session.fid;
        server_db().db_get_time_curve_data(port, deviceid, time, timetype, field, function (ret, info) {
            res.send({ ret: ret, info: info });
        });
    } else if (isJSON(power) == true) {
        var arr_pro = project_power(power, 4);
        if (arr_pro.length <= 0) {
            res.send({ ret: 1, info: [] });
            return;
        }
        server_db().db_get_time_curve_data(port, deviceid, time, timetype, field, function (ret, info) {
            res.send({ ret: ret, info: info });
        });
    } else {
        res.send({ ret: -4, info: '没有权限' });
        return;
    }
});

app.get("/protocol_field_get", function (req, res) {
    var port = 8053;
    var sobj = [];
    var fieldobj1 = {};
    var fieldobj2 = {};
    var power = req.session.power;
    if (power == '' || power == '0' || power == null) {
        res.send({ ret: -4, info: '没有权限' });
        return;
    } else if (power == 'administrator') {//超级管理员
        res.send({ ret: -1, info: "无法获取,超级管理员无法察看" });
    } else if (power == 'all') {//管理员
        // 获取设备id
        //req.query.fid = '=' + req.session.fid;
        //目前测试,只取8053

        fieldobj1.id = 'value1';
        fieldobj1.name = '值1';
        fieldobj2.id = 'value2';
        fieldobj2.name = '值2';
        sobj.push(fieldobj1);
        sobj.push(fieldobj2);

        res.send({ ret: 1, info: sobj });
    } else if (isJSON(power) == true) {
        var arr_pro = project_power(power, 4);
        if (arr_pro.length <= 0) {
            res.send({ ret: 1, info: [] });
            return;
        }
        fieldobj1.id = 'value1';
        fieldobj1.name = '值1';
        fieldobj2.id = 'value2';
        fieldobj2.name = '值2';
        sobj.push(fieldobj1);
        sobj.push(fieldobj2);
        res.send({ ret: 1, info: sobj });
    } else {
        res.send({ ret: -4, info: '没有权限' });
        return;
    }

})
// 油库的历史数据
app.get("/history_data_yk", function (req, res) {
    var table = 'yk_datasub';
    var fields = 'deviceid,dm,sensor_num,point_num,value,time';
    var power = req.session.power;
    if (power == '' || power == '0' || power == null) {
        res.send({ ret: 1, info: [] });
        return;
    } else if (power == 'all') {
        // 获取设备id
        req.query.fid = req.session.fid;
        server_db().db_select_list(null, null, req.query, fields, table, 'time', 'asc', function (ret1, info1) {
            res.send({ ret: ret1, info: info1 });
        });
    } else {
        var arr_pro = project_power(power, 4);
        if (arr_pro.length <= 0) {
            res.send({ ret: 1, info: [] });
            return;
        }
        // 获取设备id
        server_db().db_select_where_in('projectid', arr_pro, 'id,deviceid', 'device', function (ret, info) {
            if (ret == 1) {
                var deviceid_arr = [];
                for (var i = 0; i < info.length; i++) {
                    var obj = info[i];
                    deviceid_arr.push(obj.deviceid);
                }
                if (deviceid_arr.length > 0) {
                    server_db().db_select_list('deviceid', deviceid_arr, req.query, fields, table, 'time', 'asc', function (ret1, info1) {
                        res.send({ ret: ret1, info: info1 });
                    });
                } else {
                    res.send({ ret: 1, info: [] });
                }
            } else {
                res.send({ ret: ret, info: info });
            }
        });
    }
})
// 获取实时数据
app.get("/actual_data/:port", function (req, res) {
   // console.log(req,res);
    var port = parseInt(req.params.port);
    var power = req.session.power;
    if (port == null || port == '') {
        port = 8051;
    }
    if (power == '' || power == '0' || power == null) {
        res.send({ ret: 1, info: [] });
        return;
    } else if (power == 'administrator') {
        // 获取所有的设备id
        server_db().db_select_list(null, null, null, 'id,deviceid', 'device', null, null, function (ret, info) {
            if (ret == 1) {
                var deviceid_arr = [];
                for (var i = 0; i < info.length; i++) {
                    var obj = info[i];
                    deviceid_arr.push(obj.deviceid);
                }
                if (deviceid_arr.length > 0) {
                    var data = tcpcache.get_port_device_data(port, deviceid_arr);
                    res.send({ ret: 1, info: data });
                } else {
                    res.send({ ret: 1, info: [] });
                }
            } else {
                res.send({ ret: ret, info: info });
            }
        })
    } else if (power == 'all') {//管理员
        //获取设备id
        server_db().db_select_list(null, null, { fid: req.session.fid }, 'id,deviceid', 'device', null, null, function (ret, info) {
            if (ret == 1) {
                var deviceid_arr = [];
                for (var i = 0; i < info.length; i++) {
                    var obj = info[i];
                    deviceid_arr.push(obj.deviceid);
                }
                // console.log('deviceid',deviceid_arr);
                if (deviceid_arr.length > 0) {
                    var data = tcpcache.get_port_device_data(port, deviceid_arr);
                    // console.log(data);
                    res.send({ ret: 1, info: data });
                } else {
                    res.send({ ret: 1, info: [] });
                }

            } else {
                res.send({ ret: ret, info: info });
            }
        });
    } else if (isJSON(power) == true) {//普通用户
        var arr_pro = project_power(power, 4);
        if (arr_pro.length <= 0) {
            res.send({ ret: 1, info: [] });
            return;
        }
        // 获取设备id
        server_db().db_select_where_in('projectid', arr_pro, 'id,deviceid', 'device', function (ret, info) {
            if (ret == 1) {
                var deviceid_arr = [];
                for (var i = 0; i < info.length; i++) {
                    var obj = info[i];
                    deviceid_arr.push(obj.deviceid);
                }
                if (deviceid_arr.length > 0) {
                    var data = tcpcache.get_port_device_data(port, deviceid_arr);
                    res.send({ ret: 1, info: data });
                } else {
                    res.send({ ret: 1, info: [] });
                }
            } else {
                res.send({ ret: ret, info: info });
            }
        });
    } else {
        res.send({ ret: 1, info: [] });
        return;
    }
});
// 获取不同协议的数量
app.post('/protocol_data_count',function(req,res){
    var ports = req.body;
    if (ports == null || ports == '') {
        res.send({ret:-1,info:'no port'});
        return;
    }
    var sendobj = {};
    if (Array.prototype.isPrototypeOf(ports) == true) { //如果是数组
        for (var i = 0; i < ports.length; i++) {
            var port = ports[i];
            var table = pub_config.devicelog2+port;
            server_db().db_get_count_table(table, function (ret, info) {
                // console.log(ret,info);
                if (ret == 1 && info > 0) {
                    sendobj[port] = info;
                    delete_data = 1;
                    //res.send({ret:ret,info:info,port:port});
                }else{
                    sendobj[port] = 0;    
                }
                res.send({ret:detect_data, port:sendobj});
            });
        }
    } 
          
})
//获取设备总数，报警设备，正常设备
app.get('/device_count', function (req, res) {
    var power = req.session.power;
    var total = 0;
    var warn = 0;
    var ok = 0;
    if (power == '' || power == '0' || power == null) {
        res.send({ ret: 1, total: total, warn: warn, ok: ok })
        return;
    } else if (power == 'administrator') {//超级管理员
        server_db().db_get_count(null, null, 'deviceid', 'device', null, function (ret, info) {
            if (ret == 1) {
                total = info;
                server_db().db_get_count(null, null, 'deviceid', 'device', { fid: '=' + req.session.fid, status: '0' }, function (ret1, info1) {
                    if (ret1 == 1) {
                        warn = info1;
                        ok = total - warn;
                        res.send({ ret: 1, total: total, warn: warn, ok: ok })
                    } else {
                        res.send({ ret: 1, total: total, warn: warn, ok: ok })
                    }
                })
            }
        })
    } else if (power == 'all') {//管理员
        server_db().db_get_count(null, null, 'deviceid', 'device', { fid: '=' + req.session.fid }, function (ret, info) {
            if (ret == 1) {
                total = info;
                server_db().db_get_count(null, null, 'deviceid', 'device', { fid: '=' + req.session.fid, status: '0' }, function (ret1, info1) {
                    if (ret1 == 1) {
                        warn = info1;
                        ok = total - warn;
                        res.send({ ret: 1, total: total, warn: warn, ok: ok })
                    } else {
                        res.send({ ret: 1, total: total, warn: warn, ok: ok })
                    }
                })
            }
        })
    } else if (isJSON(power) == true) {//有权限普通用户
        var arr_pro = project_power(power, 4);
        if (arr_pro.length <= 0) {
            res.send({ ret: 1, total: total, warn: warn, ok: ok });
            return;
        }
        server_db().db_select_where_in('projectid', arr_pro, 'id,deviceid', 'device', function (ret, info) {
            if (ret == 1) {
                var deviceid_arr = [];
                for (var i = 0; i < info.length; i++) {
                    var obj = info[i];
                    deviceid_arr.push(obj.deviceid);
                }
                total = deviceid_arr.length;
                if (deviceid_arr.length <= 0) {
                    res.send({ ret: 1, total: total, warn: warn, ok: ok })
                } else {
                    server_db().db_get_count('deviceid', deviceid_arr, 'deviceid', 'device', { fid: '=' + req.session.fid, status: '0' }, function (ret1, info1) {
                        // console.log(ret1,info1);
                        if (ret1 == 1) {
                            warn = info1;
                            ok = total - warn;
                            res.send({ ret: 1, total: total, warn: warn, ok: ok })
                        } else {
                            res.send({ ret: 1, total: total, warn: warn, ok: ok })
                        }
                    })
                }
            }
        })
    } else {
        res.send({ ret: 1, info: [] });
        return;
    }

})

// 获取表的所有列
app.get('/table_columns/:table', function (req, res) {
    var table = req.params.table;
    if (table == null || table == "") {
        res.sendStatus(404);
        return;
    }
    server_db().db_table_columns(table, function (ret, info) {
        res.send({ ret: ret, info: info });
    })
});
/* 特定接口（不通用,宝鸡项目）：接收传感器数据:存入log表中,其他的数据存储到其他表中
  转发报警
  req.body数据格式为
  {
    data:{
      deviceid:'123456',
      press:'99',
      temp:'20'
    }
    data_ext:{

    }
  }
*/
app.post('/sensor_data/:port', function (req, res) {
    var port = parseInt(req.params.port);
    var data = req.body.data;
    var data_ext = req.body.data_ext;
    if (data_ext != null && data_ext.press_unit != null && data != null) {
        data.press_unit = data_ext.press_unit;
    }
    // console.log(data.data_ext);
    tcpcache.tcpcallback(port, data, data_ext, function (r_port, r_data) {
        // 存入数据库
        // console.log('save',r_port,r_data);
        server_db().db_get_detail_field('device', { port: r_port, deviceid: r_data.deviceid }, 'fid,projectid', function (ret, info) {
            if (ret == 1) {
                r_data.fid = info.fid;
                r_data.projectid = info.projectid;
                // 判断是否触发报警，存入报警日志表（warn_report）
                var notice_query = {
                    deviceid: '=' + r_data.deviceid,
                    fid: '=' + info.fid
                }
                var str = ' and value is not null';
                server_db().db_select_list2(null, null, notice_query, '*', 'warn_config', null, null, str, function (ret3, info3) {
                    // console.log(ret3,info3);
                    if (ret3 == 1 && info3.length > 0) {
                        for (var i = 0; i < info3.length; i++) {
                            var warninfo = info3[i];
                            var warn_type = warninfo.warn_type;
                            var value = warninfo.value;
                            var fieldname = warninfo.fieldname;
                            // 判断是否触发报警
                            if (r_data[fieldname] != null) {
                                var iswarn = is_warn(r_data[fieldname], value, warn_type, fieldname, fieldname);
                                // console.log(iswarn);
                                if (iswarn == true) {
                                    // 存入报警日志表
                                    var obj = {};
                                    obj.deviceid = r_data.deviceid;
                                    obj.fid = info.fid;
                                    obj.projectid = info.projectid;
                                    obj.warn_type = warn_type;
                                    obj.fieldname = fieldname;
                                    server_db().db_info_insert(obj, 'warn_report', function (ret2, info2) {
                                        // console.log(ret,info);
                                    })
                                    // 修改设备表的状态
                                    server_db().db_info_update({ status: '0' }, notice_query, 'device', function (ret4, info4) {
                                        // console.log(ret4,info4)
                                    });
                                }
                            }
                        }
                    }
                })
                // console.log(r_data,pub_config.devicelog);
                server_db().db_info_insert(r_data, pub_config.devicelog, function (ret1, info1) {
                    // console.log(ret1,info1);
                    res.send({ ret: ret1, info: info1 });
                })
            } else {
                // console.log('no deviceid, no save');
                res.send({ ret: 1, info: 'no save' });
            }
        })
    })
});
/*钱波新增加一个接口: 油库的传感器数据
  转发报警
  req.body数据格式为
  {
    data:{
      deviceid:'123456',
      name:'press',
      value:'99'
    }
    data_ext:{

    }
  }
*/
app.post('/sensor_data_1/:port', function (req, res) {
    var port = parseInt(req.params.port);
    var data = req.body.data;
    var data_ext = req.body.data_ext;
    tcpcache.tcpcallback(port, data, null, function (r_port, r_data) {
        // 存入数据库
        // console.log('save',r_port,r_data);
        server_db().db_get_detail_field('view_device_project', { port: r_port, deviceid: "=" + r_data.deviceid }, 'fid,projectid,type,devicename,procode', function (ret, info) {
            if (ret == 1) {
                r_data.fid = info.fid;
                r_data.projectid = info.projectid;
                // console.log(r_data);
                // 判断是否触发报警，存入报警日志表（warn_report）
                var notice_query = {
                    deviceid: '=' + r_data.deviceid,
                    fid: '=' + info.fid
                }
                var str = ' and value is not null';
                server_db().db_select_list2(null, null, notice_query, '*', 'warn_config', null, null, str, function (ret3, info3) {
                    // console.log(ret3,info3);
                    if (ret3 == 1 && info3.length > 0) {
                        for (var i = 0; i < info3.length; i++) {
                            var warninfo = info3[i];
                            var warn_type = warninfo.warn_type;
                            var value = warninfo.value;
                            var fieldname = warninfo.fieldname;
                            // 判断是否触发报警
                            var iswarn = is_warn(r_data.value, value, warn_type, fieldname, r_data.name);
                            // console.log(iswarn);
                            if (iswarn == true) {
                                // 通知用户
                                warninfo.devname = info.devicename;
                                warninfo.devtype = info.type;
                                warninfo.code = info.procode;
                                if (warninfo.notice_type == 4) {
                                    notice_user(warninfo, r_data);
                                }
                                // 存入报警日志表
                                var obj = {};
                                obj.deviceid = r_data.deviceid;
                                obj.fid = info.fid;
                                obj.projectid = info.projectid;
                                obj.warn_type = warn_type;
                                obj.fieldname = fieldname;
                                server_db().db_info_insert(obj, 'warn_report', function (ret2, info2) {
                                    // console.log(ret,info);
                                })
                                // 修改设备表的状态
                                server_db().db_info_update({ status: '0' }, notice_query, 'device', function (ret4, info4) {
                                    // console.log(ret4,info4)
                                });

                            }
                        }
                    }
                })
                server_db().db_info_insert(r_data, 'yk_datasub', function (ret, info) {
                    res.send({ ret: ret, info: info });
                })
            } else {
                // console.log('no deviceid, no save');
                res.send({ ret: 1, info: 'no save' });
            }
        })
    })
});
/* 1、（数据格式不同）接收传感器数据的接口(报警通知)
   req.body数据格式为
   {
    data:{
      deviceid:'12345',
      name:'press',
      value:'99'
    }
    data_ext:{

    }
  }
*/
app.post('/sensor_data_public/:port', function (req, res) {
    var port = parseInt(req.params.port);
    var data = req.body.data;
    var data_ext = req.body.data_ext;
    // console.log(data);
    tcpcache.tcpcallback(port, data, data_ext, function (r_port, r_data) {
        // 存入数据库
        // console.log('save',r_port,r_data);
        server_db().db_get_detail_field('view_device_project', { port: r_port, deviceid: "=" + r_data.deviceid }, 'fid,projectid,type,devicename,procode', function (ret, info) {
            // console.log(ret,info);
            if (ret == 1) {
                r_data.fid = info.fid;
                r_data.projectid = info.projectid;
                // 判断是否触发报警，存入报警日志表（warn_report）
                var notice_query = {
                    deviceid: '=' + r_data.deviceid,
                    fid: '=' + info.fid
                }
                var str = ' and value is not null';
                server_db().db_select_list2(null, null, notice_query, '*', 'warn_config', null, null, str, function (ret3, info3) {
                    // console.log(ret3,info3);
                    if (ret3 == 1 && info3.length > 0) {
                        for (var i = 0; i < info3.length; i++) {
                            var warninfo = info3[i];
                            var warn_type = warninfo.warn_type;
                            var value = warninfo.value;
                            var fieldname = warninfo.fieldname;
                            // 判断是否触发报警
                            var iswarn = is_warn(r_data.value, value, warn_type, fieldname, r_data.name);
                            // console.log(iswarn);
                            if (iswarn == true) {
                                // 通知用户
                                warninfo.devname = info.devicename;
                                warninfo.devtype = info.type;
                                warninfo.code = info.procode;
                                notice_user(warninfo, r_data);
                                // 存入报警日志表
                                var obj = {};
                                obj.deviceid = r_data.deviceid;
                                obj.fid = info.fid;
                                obj.projectid = info.projectid;
                                obj.warn_type = warn_type;
                                obj.fieldname = fieldname;
                                server_db().db_info_insert(obj, 'warn_report', function (ret2, info2) {
                                    // console.log(ret,info);
                                })
                                // 修改设备表的状态
                                server_db().db_info_update({ status: '0' }, notice_query, 'device', function (ret4, info4) {
                                    // console.log(ret4,info4)
                                });

                            }
                        }
                    }
                })
                server_db().db_info_insert(r_data, pub_config.devicelog2+port, function (ret1, info1) {
                    // console.log(ret1,info1);
                    res.send({ ret: ret1, info: info1 });
                })
            } else {
                // console.log('no deviceid, no save');
                res.send({ ret: 1, info: 'no save' });
            }
        })
    })
});
/* 2、（数据格式不同）接收传感器数据的接口(报警通知)
   req.body数据格式为
   {
    data:{
      deviceid:'123456',
      press:'99',
      temp:'20',
      value1:'21'
    }
    data_ext:{

    }
  }1517210240000
*/



var alert_obj = {};

app.post('/sensor_data_public2/:port', function (req, res) {
    var port = parseInt(req.params.port); // 端口号
    var data = req.body.data; // 数据信息
    var data_ext = req.body.data_ext;
    //console.log(data);
    // 第一步：接收到实时数据 返回r_port, r_data
    tcpcache.tcpcallback(port, data, data_ext, function (r_port, r_data) { // 存入数据库 并返回存储的端口和值
        // console.log(r_data,'info');
        // { port: r_port, deviceid: "=" + r_data.deviceid }查询条件：端口号：r_port下deviceid = r_data.deviceid 的相应字段数据
        server_db().db_get_detail_field('view_device_project', { port: r_port, deviceid: "=" + r_data.deviceid }, 'fid,projectid,type,devicename,procode', function (ret, info) {
            if (ret === 1) {
                r_data.fid = info.fid;
                r_data.projectid = info.projectid;
               // console.log(r_data,info,'info');
                var notice_query = {
                    deviceid: '=' + r_data.deviceid,
                    fid: '=' + r_data.fid
                };
                // var str = ' and value is not null';  等级报警不需要value
                // 第二步：查出数据里该设备已设置的报警字段和类型
                server_db().db_select_list2(null, null, notice_query, '*', 'warn_config', null, null, null, function (ret3, info3) {
                    if (ret3 === 1 && info3.length > 0) {
                        //console.log(ret3, info3);
                        // 第三步：循环查出的每一个字段，先判断报警类型
                        for (var i = 0; i < info3.length; i++) {

                            var warn_type = info3[i].warn_type; // 报警类型
                            var value = info3[i].value; // 接收到的值
                            var fieldname = info3[i].fieldname;// 接收到的字段
                            var notice_type = info3[i].notice_type;// 通知类型
                            var deviceid = info3[i].deviceid;// 设备id
                            var warn_grade = info3[i].warn_grade; // 该设置需要通知的等级



                            // 判断是否触发报警
                            if(warn_type === 3){ // 等级报警
                                // 第四步：判断该报警类型下是否报警；注：等级报警值大于0报警
                                if(alert_obj[fieldname] == null) {
                                    //send the alert;
                                    alert_obj[fieldname] = Date.parse(new Date());
                                    if(r_data[fieldname] !== null && r_data[fieldname] > 0){
                                        // 通过设备id获取项目id
                                        var need_proid = {
                                            deviceid: '=' + r_data.deviceid,
                                            fid: '=' + info.fid
                                        };
                                        warn_grade = r_data[fieldname];
                                        poc_fun(notice_type,warn_grade,deviceid,warn_type,need_proid,r_data.fid);
                                    }
                                }else {
                                    var t = Date.parse(new Date());
                                    if(t - alert_obj[fieldname] > 60000){
                                        //send the alert
                                        alert_obj[fieldname] = t;
                                        if(r_data[fieldname] !== null && r_data[fieldname] > 0){
                                            // 通过设备id获取项目id
                                            var need_proid = {
                                                deviceid: '=' + r_data.deviceid,
                                                fid: '=' + info.fid
                                            };
                                            warn_grade = r_data[fieldname];
                                            poc_fun(notice_type,warn_grade,deviceid,warn_type,need_proid,r_data.fid);
                                        }
                                    }
                                }

                            }else if(warn_type !== 3){ // 上下限报警和其他报警
                                if(alert_obj[fieldname] == null) {
                                    //send the alert;
                                    alert_obj[fieldname] = Date.parse(new Date());
                                    if (r_data[fieldname] !== null) {

                                        if(alert_obj[fieldname] == null) {
                                            //send the alert;
                                            alert_obj[fieldname] = Date.parse(new Date());
                                        }
                                        else {
                                            var t = Date.parse(new Date());
                                            if(t - alert_obj[fieldname] > 60000){
                                                //send the alert
                                                alert_obj[fieldname] = t;
                                            }
                                        }
                                        // 判断是否触发报警
                                        var iswarn = is_warn(r_data[fieldname], value, warn_type, fieldname, fieldname);
                                        if (iswarn) {
                                            // 通过设备id获取项目id
                                            //console.log(r_data[fieldname], value, warn_type, fieldname,'222');
                                            var need_proid = {
                                                deviceid: '=' + r_data.deviceid,
                                                fid: '=' + info.fid
                                            };
                                            poc_fun(notice_type,warn_grade,deviceid,warn_type,need_proid,r_data.fid);
                                            /*warninfo.devname = info.devicename;
                                            warninfo.devtype = info.type;
                                            warninfo.code = info.procode;
                                            //console.log(warninfo,'warninfowarninfowarninfowarninfowarninfowarninfowarninfowarninfo',r_data);
                                            notice_user(warninfo, r_data);*/
                                            // 存入报警日志表
                                            var obj = {};
                                            obj.deviceid = r_data.deviceid;
                                            obj.fid = info.fid;
                                            obj.projectid = info.projectid;
                                            obj.warn_type = warn_type;
                                            obj.fieldname = fieldname;
                                            obj.handle_status = notice_type;
                                            server_db().db_info_insert(obj, 'warn_report', function (ret2, info2) {
                                                // console.log(ret2,info2,'.............');
                                            });
                                            var obj_device = {
                                                deviceid: '=' + r_data.deviceid,
                                                fid: '=' + r_data.fid,
                                                port: '=' +port
                                            };
                                            // 修改设备表的状态
                                            server_db().db_info_update({ status: '0' }, obj_device, 'device', function (ret4, info4) {
                                                // console.log(ret4,info4)
                                            });
                                        }
                                    }
                                }else {
                                    var t = Date.parse(new Date());
                                    if(t - alert_obj[fieldname] > 60000){
                                        //send the alert
                                        alert_obj[fieldname] = t;
                                        if (r_data[fieldname] !== null) {

                                            if(alert_obj[fieldname] == null) {
                                                //send the alert;
                                                alert_obj[fieldname] = new Date();
                                            }
                                            else {
                                                var t = new Date();
                                                if(t - alert_obj[fieldname] > 60){
                                                    //send the alert
                                                    alert_obj[fieldname] = t;
                                                }
                                            }
                                            // 判断是否触发报警
                                            var iswarn = is_warn(r_data[fieldname], value, warn_type, fieldname, fieldname);
                                            if (iswarn) {
                                                // 通过设备id获取项目id
                                                //console.log(r_data[fieldname], value, warn_type, fieldname,'222');
                                                var need_proid = {
                                                    deviceid: '=' + r_data.deviceid,
                                                    fid: '=' + info.fid
                                                };
                                                poc_fun(notice_type,warn_grade,deviceid,warn_type,need_proid,r_data.fid);
                                                /*warninfo.devname = info.devicename;
                                                warninfo.devtype = info.type;
                                                warninfo.code = info.procode;
                                                //console.log(warninfo,'warninfowarninfowarninfowarninfowarninfowarninfowarninfowarninfo',r_data);
                                                notice_user(warninfo, r_data);*/
                                                // 存入报警日志表
                                                var obj = {};
                                                obj.deviceid = r_data.deviceid;
                                                obj.fid = info.fid;
                                                obj.projectid = info.projectid;
                                                obj.warn_type = warn_type;
                                                obj.fieldname = fieldname;
                                                obj.handle_status = notice_type;
                                                server_db().db_info_insert(obj, 'warn_report', function (ret2, info2) {
                                                    // console.log(ret2,info2,'.............');
                                                });
                                                var obj_device = {
                                                    deviceid: '=' + r_data.deviceid,
                                                    fid: '=' + r_data.fid,
                                                    port: '=' +port
                                                };
                                                // 修改设备表的状态
                                                server_db().db_info_update({ status: '0' }, obj_device, 'device', function (ret4, info4) {
                                                    // console.log(ret4,info4)
                                                });
                                            }
                                        }
                                    }
                                }


                            }
                        }
                    }
                });
                /*server_db().db_info_insert(r_data, pub_config.devicelog2+port, function (ret1, info1) {
                    // console.log(ret1,info1);
                    res.send({ ret: ret1, info: info1 });
                })*/
            } else {
                // console.log('no deviceid, no save');
                res.send({ ret: 1, info: 'no save' });
            }
        })
    })
});
function poc_fun(notice_type,warn_grade,deviceid,warn_type,need_proid,fid) {
    // 第五步：如果报警通过设备id和fid查出项目id
    server_db().db_select_list2(null, null, need_proid, '*', 'device', null, null, null, function (ret4, info4) {
        var role_proid = {power:  '"projectid":'+info4[0].projectid+''};
        // 第六步：通过项目id查role表，获取到该项目都有哪些角色，该角色有没有项目的权限，如果有权限，返回角色id
        server_db().db_select_list2(null, null, role_proid, '*', 'role', null, null, null, function (ret5, info5) {
            for(var i = 0; i < info5.length; i++){
                if(isJSON(info5[i].power)){
                    info5[i].power = JSON.parse(info5[i].power);
                    for(var q = 0; q < info5[i].power.length; q++){
                        if( info5[i].power[q].projectid === info4[0].projectid){
                            //console.log(info5[i].power[q].power,'power');
                            if(info5[i].power[q].power & 2 === 2 && info5[i].power[q].power & 4 === 4){
                                // 第七步：通过角色id查询都有那些用户有这些角色，返回一个数组
                                server_db().db_select_list2(null, null, {roleid: '=' + info5[i].id}, '*', 'user', null, null, null, function (ret6, info6) {
                                    if(ret6 === 1){
                                        server_db().db_get_detail( 'user', {id: '=' + fid},function (ret7, info7) {
                                            if(ret7 === 1){
                                                info6.push(info7);
                                                //console.log(info6,'info6');
                                                // 第八步：循环数组，判断通知类型，然后判断通知等级
                                                for (var j = 0;j < info6.length; j++){
                                                    info6[j].warn_grade =  parseInt(info6[j].warn_grade);
                                                    warn_grade = parseInt(warn_grade);
                                                    switch (notice_type) {
                                                        case 0://不通知
                                                            break;
                                                        case 1://短信通知
                                                            // 获取电话号码
                                                            if(info6[j].warn_grade <= warn_grade && info6[j].warn_grade > 0 ){ // 如果报警数值大于自己的报警等级值，发送通知
                                                                //console.log("等级",info6[j].tele);
                                                                public_fun.notice_user(info6[j].tele, info6[j].id, deviceid, warn_type, warn_grade, function (ret, info) {
                                                                    // console.log(ret,info);
                                                                })
                                                            }
                                                            break;
                                                        case 2://公众号通知
                                                            if(info6[j].warn_grade <= warn_grade && info6[j].warn_grade > 0 ){ // 如果报警数值大于自己的报警等级值，发送通知
                                                                if(info6[j].wx_openid !== '' && info6[j].wx_openid !== null){
                                                                    var data = {
                                                                        openid: info6[j].wx_openid,
                                                                        user: info6[j].id,
                                                                        warn_type: warn_type,
                                                                        deviceid: deviceid,
                                                                        time: current_time()
                                                                    };
                                                                    // var content = JSON.stringify(data);
                                                                    // console.log(content);
                                                                    // console.log(JSON.parse(content));
                                                                    // return;
                                                                    // console.log(data);
                                                                    post.PostData2(data, 'http://118.190.203.202:80/notice_warn', function (ret, info) {
                                                                        // console.log(ret,info);
                                                                    });
                                                                }
                                                            }
                                                            break;
                                                        case 3://短信、公众号通知
                                                            // 获取电话号码，openid
                                                            if(info6[j].warn_grade <= warn_grade && info6[j].warn_grade > 0 ){ // 如果报警数值大于自己的报警等级值，发送通知

                                                                if(info6[j].wx_openid !== '' && info6[j].wx_openid !== null){
                                                                    var data = {
                                                                        openid: info6[j].wx_openid,
                                                                        user: info6[j].id,
                                                                        warn_type: warn_type,
                                                                        deviceid: deviceid,
                                                                        time: current_time()
                                                                    };
                                                                    // var content = JSON.stringify(data);
                                                                    // console.log(content);
                                                                    // console.log(JSON.parse(content));
                                                                    // return;
                                                                    // console.log(data);
                                                                    post.PostData2(data, 'http://118.190.203.202:80/notice_warn', function (ret, info) {
                                                                        // console.log(ret,info);
                                                                    });
                                                                }
                                                                public_fun.notice_user(info6[j].tele, info6[j].id, deviceid, warn_type, warn_grade, function (ret, info) {
                                                                    // console.log(ret,info);
                                                                });
                                                            }
                                                            /*server_db().db_select_list2(null, null, query, 'tele,id,wx_openid', 'user', null, null, null, function (ret, info) {
                                                                if (ret === 1) {
                                                                    for (var i = 0; i < info.length; i++) {
                                                                        var obj = info[i];
                                                                        if (obj.tele !== null && obj.tele !== '') {
                                                                            public_fun.notice_user(obj.tele, obj.id, input.deviceid, input.warn_type, input.warn_grade, function (ret, info) {
                                                                                // console.log(ret,info);
                                                                            })
                                                                        }
                                                                        if (obj.wx_openid !== null && obj.wx_openid !== '') {
                                                                            var data = {
                                                                                openid: obj.wx_openid,
                                                                                user: obj.id,
                                                                                warn_type: input.warn_type,
                                                                                deviceid: input.deviceid,
                                                                                time: current_time()
                                                                            };
                                                                            post.PostData1(data, '118.190.203.202', 80, '/notice_warn', function (ret, info) {
                                                                                // console.log(ret,info);
                                                                            })
                                                                        }

                                                                    }
                                                                }
                                                            });*/
                                                            break;
                                                        case 4://转发通知
                                                            if (input.postaddress !== null && input.postaddress !== '') {
                                                                var json = {
                                                                    equipment_id: input.deviceid,
                                                                    equipment_name: input.devname,
                                                                    equipment_type: input.devtype,
                                                                    type: "FIRST",
                                                                    status: "异常",
                                                                    warn_infor: input_data.name + "报警,值为" + input_data.value
                                                                    // warn_time:input.time
                                                                };
                                                                var post_data = {
                                                                    type: "WARNING_INFO",
                                                                    code: input.code,//"YC_XT_XF"
                                                                    // downtime:input.time,
                                                                    busicode: random_time(true),
                                                                    data: json
                                                                };
                                                                // console.log(post_data);
                                                                post.PostData2(post_data, input.postaddress, function (ret, info) {
                                                                    // console.log(ret,info);
                                                                })
                                                            }
                                                            break;
                                                        default:
                                                    }
                                                }
                                            }
                                        });
                                    }
                                });
                            }
                        }
                    }
                }
            }
        });
    });
}
/*
 功能： 判断是否触发报警,返回true或false
 value1：接收到传感器值，
 value2: 报警表的报警值，
 warn_type: 报警表的报警类型，
      1：上限报警
      2：下限报警
      3：等级报警
      4：其他报警
 fieldname1:报警表的报警字段，
 fieldname2:接收到的报警字段
*/
// var arr = [1,2,3];
// var arr1 = JSON.stringify(arr);
// var arr2 = JSON.parse(arr1);
// console.log(arr1);
// console.log(arr2[0]);
function is_warn(value1, value2, warn_type, fieldname1, fieldname2) {
     //console.log(value1,value2,warn_type,'fieldname1');
    var flag = false;
    if (fieldname1 == fieldname2 && value1 != null && value2 != null) {
        if ((typeof value1 == 'string') && (typeof value2 == 'string')){
            //console.log(Array.prototype.isPrototypeOf(value2),value2,'zzzzz');
            if (isJSON(vlaue1) == true){
                value1 = JSON.parse(value1);
            }else {
                if (value1.indexOf("[") >= 0 && value1.indexOf("]") >= 0) {
                    value1 = value1.replace("[", "").replace("]", "");
                    value1 = value1.split(",");
                }
            }
            if (isJSON(vlaue2) == true){
                value2 = JSON.parse(value2);
            }else{
                if (value2.indexOf("[") >= 0 && value2.indexOf("]") >= 0) {
                    value2 = value2.replace("[", "").replace("]", "");
                    value2 = value2.split(",");
                }
            }

        }else{
            //console.log(value1,value2,'console.log(value1,value2,warn_type,fieldname1,fieldname2);');
            if (warn_type == 1) {
                // console.log(value1,value2,'zzzzz');
                // console.log(parseInt(value1),parseInt(value2),'zzzzz');

                if (Array.prototype.isPrototypeOf(value1) == true && Array.prototype.isPrototypeOf(value2) == true) {//如果是数组
                    // console.log(value1, value2);
                    for (var i = 0; i < value1.length; i++) {
                        if (parseInt(value1[i]) >= parseInt(value2[i])) {
                            flag = true;
                            break;
                        }
                    }
                } else if (parseInt(value1) > parseInt(value2)) {
                    // console.log(parseInt(value1),parseInt(value2));
                    flag = true;
                }
            } else if (warn_type == 2) {
                if (Array.prototype.isPrototypeOf(value1) == true && Array.prototype.isPrototypeOf(value2) == true) {//如果是数组
                    for (var i = 0; i < value1.length; i++) {
                        if (value1[i] < value2[i]) {
                            flag = true;
                            break;
                        }
                    }
                } else if (parseInt(value1) <= parseInt(value2)) {
                    flag = true;

                }
            } else if (warn_type == 3) {

            } else if (warn_type == 4) {

            }
        }


    }
    return flag;
}
// 报警通知接口
var obj = {
    id: 11,
    deviceid: '123456',
    warn_type: 1,
    notice_type: 2,
    warn_grade: '1',
    time: '2017-12-25T07:21:33.000Z',
    fid: 'min@qq.com'
}
// notice_user(obj,'123');
/*
 功能：报警通知
 input:报警通知类型
 data:报警的数据信息
*/
function notice_user(input, input_data) {
    /*
      input.notice_type:
      0: 不通知
      1: 短信通知
      2: 公众号通知
      3: 短信、公众号通知
      4: 转发给别的服务
      5: 反馈处理
    */
    // console.log(input);
    var query = {
        fid: '=' + input.fid,
        warn_grade: '0,' + input.warn_grade
    };
    switch (input.notice_type) {
        case 0://不通知
            break;
        case 1://短信通知
            // 获取电话号码
            var str = ' and tele is not null';
            server_db().db_select_list2(null, null, query, 'tele,id', 'user', null, null, str, function (ret, info) {
                if (ret === 1) {
                    for (var i = 0; i < info.length; i++) {
                        var obj = info[i];
                        public_fun.notice_user(obj.tele, obj.id, input.deviceid, input.warn_type, input.warn_grade, function (ret, info) {
                            // console.log(ret,info);
                        })
                    }
                }
            });
            break;
        case 2://公众号通知
            // 获取openid
            var str = ' and wx_openid is not null';
            server_db().db_select_list2(null, null, query, 'id,wx_openid', 'user', null, null, str, function (ret, info) {
                if (ret === 1) {
                    // console.log(ret,info);
                    for (var i = 0; i < info.length; i++) {
                        var obj = info[i];
                        if (obj.wx_openid !== '') {
                            var data = {
                                openid: obj.wx_openid,
                                user: obj.id,
                                warn_type: input.warn_type,
                                deviceid: input.deviceid,
                                time: current_time()
                            };
                            // var content = JSON.stringify(data);
                            // console.log(content);
                            // console.log(JSON.parse(content));
                            // return;
                            // console.log(data);
                            post.PostData2(data, 'http://118.190.203.202:80/notice_warn', function (ret, info) {
                                // console.log(ret,info);
                            })
                        }
                    }
                }
            });
            break;
        case 3://短信、公众号通知
            // 获取电话号码，openid
            server_db().db_select_list2(null, null, query, 'tele,id,wx_openid', 'user', null, null, null, function (ret, info) {
                if (ret === 1) {
                    for (var i = 0; i < info.length; i++) {
                        var obj = info[i];
                        if (obj.tele !== null && obj.tele !== '') {
                            public_fun.notice_user(obj.tele, obj.id, input.deviceid, input.warn_type, input.warn_grade, function (ret, info) {
                                // console.log(ret,info);
                            })
                        }
                        if (obj.wx_openid !== null && obj.wx_openid !== '') {
                            var data = {
                                openid: obj.wx_openid,
                                user: obj.id,
                                warn_type: input.warn_type,
                                deviceid: input.deviceid,
                                time: current_time()
                            };
                            post.PostData1(data, '118.190.203.202', 80, '/notice_warn', function (ret, info) {
                                // console.log(ret,info);
                            })
                        }

                    }
                }
            });
            break;
        case 4://转发通知
            if (input.postaddress !== null && input.postaddress !== '') {
                var json = {
                    equipment_id: input.deviceid,
                    equipment_name: input.devname,
                    equipment_type: input.devtype,
                    type: "FIRST",
                    status: "异常",
                    warn_infor: input_data.name + "报警,值为" + input_data.value
                    // warn_time:input.time
                };
                var post_data = {
                    type: "WARNING_INFO",
                    code: input.code,//"YC_XT_XF"
                    // downtime:input.time,
                    busicode: random_time(true),
                    data: json
                };
                // console.log(post_data);
                post.PostData2(post_data, input.postaddress, function (ret, info) {
                    // console.log(ret,info);
                })
            }
            break;
        default:

    }
}
// ***************************post接口 业务层***************************************
// 分页查询  url?a==1
// 对表的分页查询：信息列表 select:(search,select)
app.post('/list/select/:table', function (req, res) {
    // log_start.control("debug",req.body);
    // console.log(req.query);
    // console.log("power",req.session.fid,req.session.power);
    var table = req.params.table;
    if (table === null || table === "") {
        res.sendStatus(404);
        return;
    }
    var power = req.session.power;
    if (power === '' || power === '0' || power === null) {
        res.send({ ret: 1, rows: [] });
        return;
    } else if (power === 'administrator') {

    } else if (power === 'all') {
        req.query.fid = '=' + req.session.fid;
        if (table === 'logwork' || table === 'view_logwork_project') {
            req.query.statue = '=agree';
        }
    } else if (isJSON(power) === true) {//有权限的普通用户
        var arr_pro = project_power(power, 4);
        if (arr_pro.length <= 0) {
            res.send({ ret: 1, rows: [] });
            return;
        } else {
            if (table === "project") {//通过项目id获取项目列表
                req.field_arr = arr_pro;
                req.field = 'id';
            }
            else if (table === "device" || table === "view_device_project" || table === pub_config.devicelog || table === "budget" || table.indexOf(pub_config.devicelog2) >= 0) {//通过项目id获取设备列表

                req.field_arr = arr_pro;
                req.field = 'projectid';
            }
            else if (table === 'logwork' || table === 'view_logwork_project') {//公开日志
                req.field_arr = arr_pro;
                req.field = 'projectid';
                req.query.statue = '=agree';
            }
            else {
                req.query.fid = '=' + req.session.fid;
            }
        }

    } else {
        res.send({ ret: 1, rows: [] });
        return;
    }
    post_select_data(req, res, table, null);
});
app.post('/list/perworklog', function (req, res) {
    var table = 'view_logwork_project';
    var power = req.session.power;
    if (power === 'administrator') {

    } else if (power === 'all') {
        req.query.fid = '=' + req.session.fid;
    } else {
        req.query.submit_user = '=' + req.session.user;
    }
    post_select_data(req, res, table, null);
});
// 添加一条数据
app.post('/data/:table', function (req, res) {
    var table = req.params.table;
    var c = Object.keys(req.body);
    if (table === null || table === "" || c.length <= 0) {
        res.sendStatus(404);
        return;
    }
    if (table === 'device_parameters') {
        // {name:"testfieldss",type:"int(12)",des:"this is a test",first:true}
        var name = req.body.key1;
        var des = req.body.value1;
        if (name === null || des === null || name === '' || des === '') {
            res.send({ ret: -1, info: "key和value不能为空,key不能是中文" });
            return;
        }
    }
    var power = req.session.power;
    if (table === 'user') {
        req.body.pass = md5('111111');
    } else if (table === 'logwork') {
        req.body.submit_user = req.session.user;
    }
    if (power === '' || power === '0' || power === null) {//没有角色的普通用户
        if (table === 'logfile' || table === 'logwork') {
            req.body.fid = req.session.fid;
        } else {
            res.send({ ret: -4, info: '没有权限' });
            return;
        }

    } else if (power === 'administrator') {
        if (table === 'user') {
            req.body.fid = '1';
            req.body.roleid = '0';
        }
    } else if (power === 'all') {
        req.body.fid = req.session.fid;
    } else if (isJSON(power) === true) {
        if (table === 'logfile' || table === 'logwork') {
            req.body.fid = req.session.fid;
        } else if (table === 'device') {
            var arr_pro = project_power(power, 2);
            var index = arr_pro.indexOf(parseInt(req.body.projectid));
            req.body.fid = req.session.fid;
            if (index < 0) {
                res.send({ ret: -1, info: '没有权限或者没有绑定现有项目' });
                return;
            }
        } else {
            res.send({ ret: -4, info: '没有权限' });
            return;
        }
    } else {
        res.send({ ret: -4, info: '没有权限' });
        return;
    }
    // 设备参数设置
    server_db().db_info_insert(req.body, table, function (ret, info) {
        if (ret === 1) {
            res.send({ ret: ret, info: info });
        } else {
            res.send({ ret: -1, info: info });
        }

    });
});
// 添加多条数据 body: [{name:1},{name:2}]
app.post('/data_mul/:table', function (req, res) {
    var table = req.params.table;
    if (table === null || table === "" || JSON.stringify(req.body) === '{}') {
        res.sendStatus(404);
        return;
    }
    server_db().db_info_insert_mul(table, req.body, function (ret, info) {
        res.send({ ret: ret, info: info });
    })
});

// 创建协议(建表)
// var define ={
//    tableName: "alarm7",//报警信息表
//    fields: {
//        id: { des: "序号", type: "INT(11) PRIMARY KEY AUTO_INCREMENT" },
//        type: { des: "类型", type: "varchar(110)" },
//        des: { des: "描述", type: "varchar(110)" },
//        condition1: { des: "报警条件json", type: "varchar(210)" },
//        grade: { des: "等级", type: "varchar(110)" }
//    }
// }
app.post('/create_protocol', function (req, res) {
    var c = Object.keys(req.body);
    if (c.length <= 0) {
        res.sendStatus(404);
        return;
    }
    
    var table = 'protocol';
    var power = req.session.power;
    if (power == '' || power == '0' || power == null) {//没有角色的普通用户
        res.send({ ret: -4, info: '没有权限' });
        return;
    } else if (power == 'administrator') {

    } else if (power == 'all') {
        req.body.fid = req.session.fid;
    } else {
        res.send({ ret: -4, info: '没有权限' });
        return;
    }
    server_db().db_get_max(function(ret2,info2){
        if (ret2 == 1) {
            var port = parseInt(info2.port)+1;
            req.body.port = port;
            server_db().db_info_insert(req.body, table, function (ret, info) {
            if (ret == 1) {
                var define = {
                    tableName: "log_" + req.body.port,//报警信息表
                    fields: {
                        id: { des: "序号", type: "INT(11) PRIMARY KEY AUTO_INCREMENT" },
                        fid: { des: "fid", type: "varchar(100)" },
                        deviceid: { des: "deviceid", type: "varchar(100)" },
                        projectid: { des: "projectid", type: "varchar(100)" }
                    }
                }
                server_db().db_create_table(define, function (ret1, info1) {
                    res.send({ ret: ret1, info: info1 });
                })
            } else {
                res.send({ ret: -1, info: info });
            }

        });
    }
        
    })
    
});
// 添加列
// body:{name:"testfieldss",type:"int(12)",des:"this is a test",first:true}
app.post('/add_column/:table', function (req, res) {
    var table = req.params.table;
    if (table == null || table == "" || req.body == null) {
        res.sendStatus(404);
        return;
    }
    server_db().db_add_column(table, req.body, function (ret, info) {
        res.send({ ret: ret, info: info });
    })
});
// ***************************put接口***************************************
// 修改密码 编辑一条数据 url?id==5
app.put('/modifypass', function (req, res) {
    var table = 'user';
    var pass = req.body.pass;
    var oldpass = req.body.oldpass;
    var c = Object.keys(req.query);
    if (pass == null || pass == '' || c.length <= 0 || oldpass == null || oldpass == '') {
        res.sendStatus(404);
        return;
    }
    delete req.body.oldpass;
    req.body.pass = md5(pass);
    oldpass = md5(oldpass);
    server_db().db_get_detailuser(table, req.query, function (ret, info, power) {
        if (ret == -1) {
            res.send({ ret: -1 });
        }
        else if (ret == 0) {
            res.send({ ret: 0 });
        }
        else if (ret == 1) {
            if (info.pass == oldpass) {
                server_db().db_info_update(req.body, req.query, table, function (ret, info) {
                    res.send({ ret: ret, info: info });
                });

            } else {
                res.send({ ret: -1, info: '原始密码错误' })
            }
        }
    });
});
// 下发查询的接口
app.post('/query_device/:port', function (req, res) {
    var deviceid = req.body.deviceid;
    var port = parseInt(req.params.port);
    if (deviceid == null || deviceid == '') {
        res.send({ret:-1,info:'no deviceid'});
        return;
    }
    if (port == null || port == '') {
        res.send({ret:-1,info:'no port'});
        return;
    }
    req.body.cmd = 'read';
    // console.log(req.body);
    var data = JSON.stringify(req.body);
    // var message = Buffer.from('00000000');
    client.send(data, 0, data.length, port, 'localhost');
    // client.on('message', function(msg){
    //     console.info('msg')
    // });
    var data = tcpcache.get_port_device_data_1(port, deviceid);
    res.send({ ret: 1, info: data });
});
// 参数设置的接口
app.put('/edit_device/:port', function (req, res) {
    var deviceid = req.query.deviceid;
    var id = req.query.id;
    var port = parseInt(req.params.port);
    var table = 'device';
    if (deviceid != null && deviceid.indexOf('=') >= 0) {
        deviceid = deviceid.match(/=(\S*)/)[1];
    }
    if (deviceid == null || deviceid == '' || id == '' || id == null) {
        res.send({ret:-1,info:'no deviceid'});
        return;
    }
    if (port == null || port == '') {
        res.send({ret:-1,info:'no port'});
        return;
    }
    var write_data = req.body;
    // var cun_data = {};
    // Object.assign(cun_data,req.body);
    // var message = Buffer.from('00000000');
    // client.on('message', function(msg){
    //     console.info('msg')
    // });
    var power = req.session.power;
    if (power == '' || power == '0' || power == null) {//没有角色的普通用户
        res.send({ ret: -4, info: '没有权限' });
        return;
    } else if (power == 'all') {
        req.body.fid = req.session.fid;
    } else if (power == 'administrator') {

    } else if (isJSON(power) == true) {//有权限普通用户
        var arr_pro = project_power(power, 2);
        if (arr_pro.length <= 0) {
            res.send({ ret: -4, info: '没有权限' })
        } else {
            // 获取设备表的id
            server_db().db_select_where_in('projectid', arr_pro, 'id,deviceid', 'device', function (ret, info) {
                if (ret == 1) {
                    var deviceid_arr = [];
                    for (var i = 0; i < info.length; i++) {
                        var obj = info[i];
                        deviceid_arr.push(obj.id);
                    }
                    var str = req.query.id;
                    if (str != null && str.indexOf('=') >= 0) {
                        str = str.match(/=(\S*)/)[1];
                    }
                    var index = deviceid_arr.indexOf(parseInt(str));
                    // console.log(power,arr_pro,deviceid_arr,req.query.id,str);
                    if (index >= 0) {
                        server_db().db_info_update(req.body, req.query, table, function (ret, info) {
                            res.send({ ret: ret, info: info });
                            if (ret == 1) {
                                write_data.deviceid = deviceid;
                                write_data.cmd = 'write';
                                var data = JSON.stringify(write_data);
                                client.send(data, 0, data.length, port, 'localhost');
                            }
                        });
                    } else {
                        res.send({ ret: -4, info: '没有权限' });
                    }
                }
            });
        }
        return;
    } else {
        res.send({ ret: -4, info: '没有权限' });
        return;
    }
    server_db().db_info_update(req.body, req.query, table, function (ret, info) {
        res.send({ ret: ret, info: info });
        if (ret == 1) {
            write_data.deviceid = deviceid;
            write_data.cmd = 'write';
            // console.log(write_data);
            var data = JSON.stringify(write_data);
            client.send(data, 0, data.length, port, 'localhost');
        }
    });
});
// 编辑一条数据 url?id==5   (参数设置接口)
app.put('/data/:table', function (req, res) {
    // console.log(req.query,req.body);
    var table = req.params.table;
    var c = Object.keys(req.query);
    if (table == null || table == "" || req.body == null || c.length <= 0) {
        res.sendStatus(404);
        return;
    }
    var power = req.session.power;
    if (power == '' || power == '0' || power == null) {//没有角色的普通用户
        if (table == 'user') {
            req.body.fid = req.session.fid;
        } else {
            res.send({ ret: -4, info: '没有权限' });
            return;
        }
    } else if (power == 'all') {
        if (table == 'user' && (req.query.id == ("=" + req.session.fid) || req.query.id == req.session.fid)) {
            req.body.fid = '1';
        } else {
            req.body.fid = req.session.fid;
        }
    } else if (power == 'administrator') {
        if (table == 'user') {
            req.body.fid = '1';
            req.body.roleid = '0';
        }
    } else if (isJSON(power) == true) {//有权限普通用户
        if (table == 'device') {
            var arr_pro = project_power(power, 2);
            if (arr_pro.length <= 0) {
                res.send({ ret: -4, info: '没有权限' })
            } else {
                // 获取设备表的id
                server_db().db_select_where_in('projectid', arr_pro, 'id,deviceid', 'device', function (ret, info) {
                    if (ret == 1) {
                        var deviceid_arr = [];
                        for (var i = 0; i < info.length; i++) {
                            var obj = info[i];
                            deviceid_arr.push(obj.id);
                        }
                        var str = req.query.id;
                        if (str != null && str.indexOf('=') >= 0) {
                            str = str.match(/=(\S*)/)[1];
                        }
                        var index = deviceid_arr.indexOf(parseInt(str));
                        // console.log(power,arr_pro,deviceid_arr,req.query.id,str);
                        if (index >= 0) {
                            server_db().db_info_update(req.body, req.query, table, function (ret, info) {
                                res.send({ ret: ret, info: info });
                            });
                        } else {
                            res.send({ ret: -4, info: '没有权限' });
                        }
                    }
                });
            }
            return;
        } else if (table == 'project') {
            var arr_pro = project_power(power, 1);
            if (arr_pro.length <= 0) {
                res.send({ ret: -4, info: '没有权限' })
            } else {
                var str = req.query.id;
                if (str != null && str.indexOf('=') >= 0) {
                    str = str.match(/=(\S*)/)[1];
                }
                var index = arr_pro.indexOf(parseInt(str));
                if (index >= 0) {
                    server_db().db_info_update(req.body, req.query, table, function (ret, info) {
                        res.send({ ret: ret, info: info });
                    });
                } else {
                    res.send({ ret: -4, info: '没有权限' });
                }
            }
            return;
        } else if (table == 'user') {
            req.body.fid = req.session.fid;
        }else {
            res.send({ ret: -4, info: '没有权限' });
            return;
        }
    } else {
        res.send({ ret: -4, info: '没有权限' });
        return;
    }
    server_db().db_info_update(req.body, req.query, table, function (ret, info) {
        res.send({ ret: ret, info: info });
    });

});
// 修改表的列
app.put('/column/:table/:columnname', function (req, res) {
    var table = req.params.table;
    var column = req.params.columnname;
    if (table == null || table == "" || req.body == null || column == null) {
        res.sendStatus(404);
        return;
    }
    server_db().db_edit_column(table, column, req.body, function (ret, info) {
        res.send({ ret: ret, info: info });
    })
});
// ***************************delete接口***************************************
// 删除一条数据 url?id==123
app.delete('/data/:table', function (req, res) {
    var table = req.params.table;
    var query = req.query;
    if (table == null || table == "") {
        res.sendStatus(404);
        return;
    }
    var power = req.session.power;
    if (power == '' || power == '0' || power == null) {//没有角色的普通用户
        res.send({ ret: -4, info: '没有权限' });
        return;
    } else if (power == 'all') {

    } else if (power == 'administrator') {

    } else if (isJSON(power) == true) {
        if (table == 'device') {
            var arr_pro = project_power(power, 2);
            if (arr_pro.length <= 0) {
                res.send({ ret: -4, info: '没有权限' })
            } else {
                // 获取设备表的id
                server_db().db_select_where_in('projectid', arr_pro, 'id,deviceid', 'device', function (ret, info) {
                    if (ret == 1) {
                        var deviceid_arr = [];
                        for (var i = 0; i < info.length; i++) {
                            var obj = info[i];
                            deviceid_arr.push(obj.id);
                        }
                        var str = query.id;
                        if (str != null && str.indexOf('=') >= 0) {
                            str = str.match(/=(\S*)/)[1];
                        }
                        var index = deviceid_arr.indexOf(parseInt(str));
                        if (index >= 0) {
                            server_db().db_info_delete(query, table, function (ret, info) {
                                res.send({ ret: ret, info: info });
                            });
                        } else {
                            res.send({ ret: -4, info: '没有权限' });
                        }
                    }
                });
            }
            return;
        } else {
            res.send({ ret: -4, info: '没有权限' });
            return;
        }
    } else {
        res.send({ ret: -4, info: '没有权限' });
        return;
    }
    // 设备参数设置
    server_db().db_info_delete(query, table, function (ret, info) {
        res.send({ ret: ret, info: info });
    });

});
// 删除多行数据 url?field=['a','b']
app.delete('/data_mul/:table', function (req, res) {
    var table = req.params.table;
    var query = req.query;
    if (table == null || table == "" || JSON.stringify(query) == '{}') {
        res.sendStatus(404);
        return;
    }
    var field, arr;
    for (var key in query) {
        field = key;
        arr = query[key];
    }
    server_db().db_info_delete_mul(table, field, arr, function (ret, info) {
        res.send({ ret: ret, info: info });
    })
});
// 删除一个协议(删除协议，删除协议的数据表)
app.delete('/sensor/protocol', function (req, res) {
    var table = 'protocol';
    var query = req.query;
    var table2 = 'log_';
    var c = Object.keys(req.query);
    if (c.length <= 0 || query.id == null) {
        res.sendStatus(404);
        return;
    }
    if (query.port == null || query.port == '') {
        res.send({ret:-1,info:'no port'});
        return;
    }
    // if (query.id[0] == "=") {
    //     var len = query.id.length;
    //     table2 += query.id.substr(1, len - 1);
    // } else {
    //     table2 += query.id;
    // }
    table2 += query.port;
    var power = req.session.power;
    if (power == '' || power == '0' || power == null) {//没有角色的普通用户
        res.send({ ret: -4, info: '没有权限' });
        return;
    } else if (power == 'all') {

    } else if (power == 'administrator') {

    } else {
        res.send({ ret: -4, info: '没有权限' });
        return;
    }
    server_db().db_info_delete(query, table, function (ret, info) {
        if (ret == 1) {
            server_db().db_delete_table(table2, function (ret1, info1) {
                res.send({ ret: ret1, info: info1 });
            })
        } else {
            res.send({ ret: -1, info: info });
        }
    });

});
// 删除表中的一列
app.delete('/column/:table/:column', function (req, res) {
    var table = req.params.table;
    var column = req.params.column;
    if (table == null || table == '' || column == null || column == '') {
        res.sendStatus(404);
        return;
    }
    server_db().db_delete_column(table, column, function (ret, info) {
        res.send({ ret: ret, info: info });
    })
});
// ********************************函数******************************************
function random_time(flag) {
    var str = '';
    var oDate = new Date(); //实例一个时间对象；
    str += oDate.getFullYear();   //获取系统的年；
    var month = oDate.getMonth() + 1;   //获取系统月份，由于月份是从0开始计算，所以要加1
    if (month >= 1 && month <= 9) {
        month = "0" + month;
    }
    str += month;
    var strDate = oDate.getDate(); // 获取系统日，
    if (strDate >= 0 && strDate <= 9) {
        strDate = "0" + strDate;
    }
    str += strDate;
    var hour = oDate.getHours(); //获取系统时，
    if (hour >= 0 && hour <= 9) {
        hour = "0"+hour;
    }
    str += hour;
    var min = oDate.getMinutes(); //分
    if (min >= 0 && min <= 9) {
        min = "0"+min;
    }
    str += min;
    var sen = oDate.getSeconds(); //秒 
    if (sen >= 0 && sen <= 9) {
        sen = "0"+sen;
    }
    str += sen; //秒    
    // 6位随机数
    if (flag == true) {
        for (var i = 0; i < 6; i++) {
            str += Math.floor(Math.random() * 10);
        }
    }   
    return str;
}
function current_time() {
    var str = '';
    var oDate = new Date(); //实例一个时间对象；
    str += oDate.getFullYear();   //获取系统的年；
    var month = oDate.getMonth() + 1;   //获取系统月份，由于月份是从0开始计算，所以要加1
    if (month >= 1 && month <= 9) {
        month = "0" + month;
    }
    str += "-";
    str += month;
    var strDate = oDate.getDate(); // 获取系统日，
    if (strDate >= 0 && strDate <= 9) {
        strDate = "0" + strDate;
    }
    str += "-";
    str += strDate;
    str += " ";
    var hour = oDate.getHours(); //获取系统时， 
    if (hour >= 0 && hour <= 9) {
        hour = "0"+hour;
    }   
    str += hour;
    str += ":";
    var min = oDate.getMinutes(); //分 
    if (min >= 0 && min <= 9) {
        min = "0"+min;
    }   
    str += min;
    str += ":";
    var sen = oDate.getSeconds(); //秒 
    if (sen >= 0 && sen <= 9) {
        sen = "0"+sen;
    } 
    str +=  sen;  
    return str;
}
// ******************************测试数据************************************************
app.delete('/data1/delete', function (req, res) {
    // console.log(req.body);
    res.send({ ret: 1, info: req.body });
});
http.listen(9069, function () {
    console.log('info', "listening on *:9069 construct");
});
// var r = Math.random() * 0x10000 | 0;
// var name1 = 'file.originalname1122222211111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111122';
// var name2 ='name2gadkhdfjghkjdafhjdkagholad9999999999999999999999999999999999999999999999999999999';
// var name = name1+name2;
// console.log(name.length,name1.length,name2.length);
// if (name.length > 255) {
//     var left = name.length - 255;
//     var name1_length = name1.length;
//     console.log(name1_length,left);
//     name1 = name1.substr(0,name1_length-left-1); 
//     name = name1+name2;
// }
// console.log(name);